package com.liyunc.demo.bundle.security.filter;

import com.liyunc.demo.bundle.security.model.BaseCredential;
import com.liyunc.demo.comp.auth.AuthenticatedUser;
import com.liyunc.demo.comp.auth.Authenticator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * @author liyuncong
 * @version 1.0
 * @file BaseAuthProvider.java
 * @brief BaseAuthProvider
 * @details BaseAuthProvider
 * @date 2022-03-31
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-03-31     liyuncong          Created
 */
@Component
public class BaseAuthProvider extends AbstractAuthProvider {

    @Autowired
    private Authenticator<Object> authenticator;

    public BaseAuthProvider() {
        super(BaseCredential.class);
    }

    @Override
    public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {
        if (authentication instanceof BaseCredential credential) {
            AuthenticatedUser<Object> authUser =
                authenticator.authenticate(
                    String.valueOf(credential.getPrincipal()),
                    String.valueOf(credential.getCredentials())
                );
            return buildAuthAccount(authUser);
        }
        return null;
    }
}
